let websocket = null;
let isConnected = false;  // 用于追踪WebSocket连接状态

// 默认在页面加载时开启连接
window.onload = function() {
    openWebSocket();  // 默认开启连接
    updateButtonState(true);  // 默认按钮状态为"关闭连接"
};

// 判断当前浏览器是否支持WebSocket
function openWebSocket() {
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:9004/websocket/spark-ai");

        // 连接打开
        websocket.onopen = () => {
            addStatusMessage("WebSocket连接已开启", "connected");
            isConnected = true;  // 更新连接状态
            updateButtonState(true);  // 更新按钮状态
        };

        // 收到消息
        websocket.onmessage = function (message) {
            const html = new showdown.Converter().makeHtml(message.data);
            displayMessage(html, 'bot');
        };

        // 连接断开
        websocket.onclose = () => {
            addStatusMessage("WebSocket连接已关闭", "closed");
            isConnected = false;  // 更新连接状态
            updateButtonState(false);  // 更新按钮状态
        };

        // 异常
        websocket.onerror = () => displayMessage("WebSocket连接发生错误", 'system');
    } else {
        alert('当前浏览器不支持 websocket');
        throw new Error('Browser does not support WebSocket.');
    }
}

// 切换WebSocket连接状态
function toggleWebSocket() {
    if (isConnected) {
        closeWebSocket();  // 如果连接已开启，点击按钮关闭连接
    } else {
        openWebSocket();  // 如果连接已关闭，点击按钮开启连接
    }
}

// 关闭 WebSocket 连接
function closeWebSocket() {
    if (websocket) {
        websocket.close();
    }
}

// 更新按钮状态（颜色和文案）
function updateButtonState(isConnected) {
    const wsButton = document.getElementById('ws-toggle-btn');
    if (isConnected) {
        wsButton.style.backgroundColor = '#f44336';  // 红色
        wsButton.textContent = '关闭连接';
    } else {
        wsButton.style.backgroundColor = '#4CAF50';  // 绿色
        wsButton.textContent = '开启连接';
    }
}

// 将消息显示在网页上
function displayMessage(message, sender) {
    const chatBox = document.getElementById('chat-box');
    const messageElement = document.createElement('div');
    messageElement.classList.add('message', `${sender}-message`);

    let timestamp = '';
    if (sender === 'user' || sender === 'bot') {
        timestamp = `<span class="timestamp">${getCurrentDateTime()}</span>`;
    }

    messageElement.innerHTML = `<span class="message-bubble">${message}</span>${timestamp}`;
    chatBox.appendChild(messageElement);
    chatBox.scrollTop = chatBox.scrollHeight;  // 滚动到底部
}

// 获取当前日期和时间
function getCurrentDateTime() {
    const now = new Date();
    return now.toLocaleString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit', year: 'numeric', month: '2-digit', day: '2-digit' });
}

// 新增状态消息
function addStatusMessage(message, className) {
    const statusMessage = document.createElement('div');
    statusMessage.classList.add('status-message', className);
    statusMessage.textContent = message;
    document.getElementById('chat-box').appendChild(statusMessage);
    document.getElementById('chat-box').scrollTop = document.getElementById('chat-box').scrollHeight;
}

// 发送消息
function sendMessage() {
    const message = document.getElementById('message').value;
    if (!message.trim()) return;

    // 显示用户输入的消息
    displayMessage(message, 'user');

    // 清空输入框
    document.getElementById('message').value = '';

    // 发送消息到 WebSocket
    if (websocket && websocket.readyState === WebSocket.OPEN) {
        websocket.send(message);
    } else {
        alert('WebSocket未连接');
    }
}

// 监听Enter键发送消息
document.getElementById('message').addEventListener('keydown', function (e) {
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();  // 防止换行
        sendMessage();
    }
});
